<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\DistributionShopOrderModel;
use My\Model\DistributionShopRateModel;
use Utuo\PHPExcel;
use Home\Logic\DistributionShopPayLogic;
//use My\Controller\UploadController;

class DistributionShopOrderController extends BackgroundController {
	
	private $deliverMethod = array(
		'0' => '物流',
		'1' => '无需配送',
	);
	
	/* 订单类型 */
	protected $orderTypes = array(
			0 => '待发货',
			1 => '交易成功',
			3 => '待买家签收',
			4 => '待卖家审核评价',
			5 => '待买家付款',
			7 => '已支付订单',
			6 => '退款订单',
			2 => '全部',
	);
	
	public function _initialize() {
		$this->setControllerTitle("订单管理");
		$this->setActionTitle(array(
			'index' => '订单列表',
			'deliver' => '发货',
			'detials' => '订单详细',
			'comment' => '评价',
			'showUserOrderList' => '用户分销的商品列表',
			'importexl'=>'导入excel',
			'refundOrder' => '订单退款',
			
		));
		$this->setActionNav("index,refundOrder");
		ACTION_NAME == "actForSign" and \Think\Hook::add('disorder_completed', 'Home\\Behaviors\\DistributionShopOrderCompletedBehavior');
	}
	
	/**
	 * 获得查询参数
	 * @return $params
	 * array(
	 * 	 'agentId', // 代理id*
	 * 	 'type' // 类型 *
	 * 	 'tel' // 收货人电话
	 * 	 'consignee' // 收货人
	 * 	 'orderId' // 订单id
	 * )
	 */
	private function getParams() {
		$agentId = I('agentId', -1, "intval");
		$type = I("type", 0);
		$consignee = I("consignee");
		$openId = I("openId");
		$orderId = I("orderId");
		$tel = I("tel");
		$timeType = I("timeType", 0, "intval");
		$params = array();
		
		/* 订单id */
		if ( !empty($orderId) ) {
			$params['orderId'] = $orderId;
		}
		
		/* 代理id(*)  */
		if ( $agentId*1 > 0 ) {
			$agent = M("Agent")->where("id=%d", $agentId)->find();
			if ( !$agent ) {
				$agentId = -1;
			}
		} elseif ( $agentId*1 === -1 ) {
			// 全部
		} elseif ( $agentId*1 === 0 ) { 
			// 总商家
		} else {
			$agentId = -1;
		}
		$params['agentId'] = $agentId;
		
		/* 类型(*) */
		if ( !in_array( $type, array_keys( $this->orderTypes ) ) ) {
			$type = 2;
		}
		$params['type'] = $type;
		
		/* 收货人电话  */
		if ( !empty($tel) ) {
			$params['tel'] = $tel;
		}
		
		/* 收货人  */
		if ( !empty($consignee) ) {
			$params['consignee'] = $consignee;
		}
		
		/* 收货人  */
		if ( !empty($openId) ) {
			$params['openId'] = $openId;
		}
		
		/* 时间 */
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params['startDate'] = $startDate;
		$params['endDate'] = $endDate;
		$params['timeType'] = $timeType;
		
		return $params;
	}
	
	/**
	 * 获得参数与查询条件
	 */
	private function getCondition( $params ) {
		$agentId = $params['agentId'];
		$type = $params['type'];
		$consignee = $params['consignee'];
		$orderId = $params['orderId'];
		$tel = $params['tel'];
		$openId = $params['openId'];
		$timeType = $params['timeType'];
		$startDate = $params['startDate'];
		$endDate = $params['endDate'];
		
		$condition = array( 'orders.cid' => $this->aid, 'orders.is_deleted' => 0);
		
		/** 筛选条件 */
		if ( !empty($orderId) ) {
			$condition['orders.order_id'] = $orderId;
		}
		
		if ( $agentId*1 >= 0 ) {
			 $condition['orders.agent_id'] = $agentId;
		}
		
		/* 类型 */
		if( $type == 0 ) { // 待发货
			$condition['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_SHIPPING;
		} elseif ($type == 1) { // 交易成功
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
		} elseif($type == 3) { // 待买家签收
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_SIGN;
		} elseif($type == 4) { // 待卖家完成评价
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
			$condition ['orders.rate_status'] = array('in', array(DistributionShopRateModel::RATE_STATUS_BUYER)) ;
		} elseif($type == 5) { // 待买家付款
			$condition ['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_PAY;
			$condition ['orders.pay_status'] = DistributionShopOrderModel::PAY_STATUS_NOT_PAID;
		} elseif($type == 6) {
			$condition['orders.refund_status'] = array('in', array(
					DistributionShopOrderModel::ORDER_REFUND_STATUS_ON,
					DistributionShopOrderModel::ORDER_REFUND_STATUS_FINISH,
				),
			);
		} elseif($type == 7) {
			$condition ['orders.pay_status'] = DistributionShopOrderModel::PAY_STATUS_PAID;
			$condition ['orders.refund_status'] = 0; // 非退款订单
		}
		
		/* 收货人电话  */
		if ( !empty($tel) ) {
			$condition['orders.tel'] = $tel;
		}
		
		/* 收货人  */
		if ( !empty($consignee) ) {
			$condition['orders.consignee'] = array('like', "%{$consignee}%");
		}
		
		/* openId  */
		if ( !empty($openId) ) {
			$condition['user.openId'] = array('eq', "{$openId}");
		}
		
		/* 时间  */
		$condition['orders.'.($timeType?'pay_time':'create_time')] = array('between', array($startDate, $endDate));
		
		return $condition;
	}
	
	/**
	 * 订单列表
	 */
	public function indexAction() {
		$belongs = array(
				'-1' => '全部',
				'0' => '总商家',
		);
		$times = array(
		    '0' => '下单时间',
		    '1' => '支付时间',
		);
		$this->setActionLink();
		$dso = D("DistributionShopOrder");
		$d = D("DistributionShopOrder orders");
		$params = $this->getParams();
		$condition = $this->getCondition($params);
		/* 查询  */
		$condition['user.id'] = array('exp', 'is not null');
		$productOrderLists = $d->join("__WECHAT_USER__ user on user.id=orders.uid", "LEFT")->where($condition)->field("orders.*,user.nickname,user.openId")->limit($this->getPageSize())->page($this->getPage())->order("id desc")->select();
		$productOrderCount = $d->join("__WECHAT_USER__ user on user.id=orders.uid", "LEFT")->where($condition)->count();
		$dso->bindOrderDetail ( $productOrderLists, 0 );
		foreach ($productOrderLists as &$v) {
			$v["orderShowStatus"] = $dso->getOrderShowStatus($v);
			$this->getOperate($v);
		}
		if ( $params['agentId']*1 > 0 ) {
			$agent = M("Agent")->where("id=%d", $params['agentId'])->find() and $belongs[$agent['id']] = $agent['name'];
		}
		$this->assign("belongsOptions", $this->getOption($belongs, $params['agentId']));
		$this->assign("timeTypeOptions", $this->getOption($times, $params['timeType']));
		$this->assign("orderTypesOptions", $this->getOption($this->orderTypes, $params['type']));
		$this->assign("params", $params);
		$this->showPage($productOrderCount, $this->getPageSize(), $params);
		$this->assign("productOrderLists", $productOrderLists);
		$this->display();
	}
	
	/**
	 * 导出Excel
	 */
	public function exportXLSAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params );
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("微美风铃")
					->setLastModifiedBy("微美风铃")
					->setTitle("销售报表")
					->setSubject("销售报表")
					->setDescription("销售报表")
					->setKeywords("销售 报表")
					->setCategory("报表");
	
	
		/*设置标题*/
		$titles = array('订单编号','商品总计','订单运费','订单合计','收件人','省','市','区','地址','电话','下单时间','支付时间','产品名称','数量','拍下价格','规格');
		$fields = array('order_id'=> array('type'=>'string'),
				'goods_amount'=> array('type'=>'string'),
				'shipping_fee' => array('type'=>'string'),
				'total' => array('type'=>'string'),
				'consignee' => array('type'=>'string'),
    		    'provinceName' => array('type'=>'string'),
    		    'cityName' => array('type'=>'string'),
    		    'areaName' => array('type'=>'string'),
    		    'address' => array('type'=>'string'),
				'tel' => array('type'=>'string'),
				'create_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
		        'pay_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
				'product_name' => array('type'=>'string'),
				'product_number' => array('type'=>'string'),
				'product_price' => array('type'=>'string'),
				'product_attr' => array('type'=>'string'));
		$sheet0 = $objPHPExcel->setActiveSheetIndex(0);
		$rowNumber = 1;
		foreach ($titles as $k => $v) {
			$sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
		}
		$rowNumber++;
		foreach ( $productOrderGoodsLists as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
				$sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
				//$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
			}
			$rowNumber++;
		}
		$objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1'); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	
	/**
	 * 导出
	 */
	public function exportOrderXLSAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params, false );
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("微美风铃")
					->setLastModifiedBy("微美风铃")
					->setTitle("销售报表")
					->setSubject("销售报表")
					->setDescription("销售报表")
					->setKeywords("销售 报表")
					->setCategory("报表");
	
	
		/*设置标题*/
		$titles = array('订单编号','商品总计','订单运费','订单合计','收件人','省','市','区','地址','电话','下单时间','支付时间','订单状态');
		$fields = array('order_id'=> array('type'=>'string'),
				'goods_amount'=> array('type'=>'string'),
				'shipping_fee' => array('type'=>'string'),
				'total' => array('type'=>'string'),
				'consignee' => array('type'=>'string'),
    		    'provinceName' => array('type'=>'string'),
    		    'cityName' => array('type'=>'string'),
    		    'areaName' => array('type'=>'string'),
				'address' => array('type'=>'string'),
				'tel' => array('type'=>'string'),
				'create_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
		        'pay_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
				'orderStatusName' => array('type'=>'string'),);
		$sheet0 = $objPHPExcel->setActiveSheetIndex(0);
		$rowNumber = 1;
		foreach ($titles as $k => $v) {
			$sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
		}
		$rowNumber++;
		foreach ( $productOrderGoodsLists as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
				$sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
				//$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
			}
			$rowNumber++;
		}
		$objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1'); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}	
	
																	   /**
																	   * 导入快递单号
																	   * 
																	   */
public function importexlAction(){
	
	$upload = new Upload();// 实例化上传类
	$upload->maxSize = 3145728 ;// 设置附件上传大小
	$upload->exts = array('jpg', 'gif', 'png', 'jpeg','xls');// 设置附件上传类型
	$upload->rootPath  =     './Public/'; 
	// 上传文件
	$info = $upload->upload();
	var_dump($info);die;
	$this->$this->ajaxSuccess("上传成功", $info);
	if(!$info){// 上传错误提示错误信息
$this->error($upload->getError());
}else{// 上传成功
	$files='./Public/'.$info['savepath'].$info['savename'];
	$PHPExcel = new PHPExcel();
	$PHPReader = new PHPExcel_IOFactory();
	$xlsPath =$files ;
	$type = 'Excel5';
	$xlsReader = $PHPReader->createReader($type);
	$xlsReader->setReadDataOnly(true);
	$xlsReader->setLoadSheetsOnly(true);
	$Sheets = $xlsReader->load($xlsPath);
	$Sheet = $Sheets->getSheet(0)->toArray();
	foreach($Sheet as $k=>$v){ 
		//$model = M('student');// 取得成功上传的文件信息
		$data['name']=$v[0];
		//$result=$model->add($data);
		var_dump($data);
		if($result){
			$this->success("入库成功");
		}else{
			$this->error("入库失败");
		}
	}
}

}


	
	/**
	 * 查询
	 * @param array $params 查询条件
	 * @param bool 是否显示详细
	 * @return Ambigous <\Think\mixed, string, boolean, NULL, multitype:, mixed, object>
	 */
	private function search( $params, $detail = true ) {
		$params = $this->getParams();
		$condition = $this->getCondition($params);
		$orders = D("DistributionShopOrder orders");
		$fields = "orders.order_id,orders.goods_amount,orders.shipping_fee,orders.goods_amount+orders.shipping_fee as total,orders.create_time,orders.pay_time,orders.order_status,orders.pay_status".
				",orders.consignee
		         ,province.name as provinceName, city.name as cityName, area.name as areaName, orders.address
		         ,concat(CASE WHEN province.name is NULL THEN '' ELSE province.name END, ' ', CASE WHEN city.name is NULL THEN '' ELSE city.name END,' ', CASE WHEN area.name is NULL THEN '' ELSE area.name END,' ',CASE WHEN orders.address is NULL THEN '' ELSE orders.address END) as fullAddress
		         ,orders.tel";
		if ( $detail ) {
			$orders->join('__DISTRIBUTION_SHOP_ORDER_GOODS__ goods on orders.id=goods.order_id');
			$fields.=",goods.product_name,goods.product_number,goods.product_price,goods.product_attr";
		}
		$result = $orders->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
						->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
						->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
						->where( $condition )
						->field( $fields )
						->order('orders.province asc,orders.city asc,orders.area asc')
						->select();
		foreach ( $result as $k => &$v ) {
			$v['orderStatusName'] = D("DistributionShopOrder")->getOrderShowStatus ( $v );
		}
		return $result;
	}
		
	// 发货
	public function deliverAction() {
		$d = D("DistributionShopOrder");
		$orderId = I("id", 0);
		$productOrder = $d->where(array(
							'cid' => $this->aid,
							'id' => $orderId,
						))->find();
		$this->assign("productOrder", $productOrder);
		$this->display();
	}
	
	// 发货提交
	public function deliverPostAction() {
		$d = D("DistributionShopOrder");
		$orderId = I("id", 0, "intval");
		// 验证
		$order = $d->where(array( "cid" => $this->aid, "id" => $orderId))->find();
		$order or $this->ajaxError("订单不存在");
		$d->field('deliver_method,express_name,shipping_no,deliverman_uid')->create();
		$data = array(
				'shipping_time' => time(),
				'expect_take_time' => time() + 7 * 24 * 3600,
		);
		if( $d->deliver_method == 0 ) {
			$data['express_name'] = $d->express_name or $this->ajaxError("请选择快递名称.");
			$data['shipping_no'] = $d->shipping_no or $this->ajaxError("请填写物流单号.");
		} elseif( $d->deliver_method == 1 ) {
			// 无需配送
		} else {
			$this->ajaxError("没有您选择的配送方式");
		}
		$data['deliver_method'] = $d->deliver_method;
			
	    if ( $order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN ) {
	        false !== $d->where(array( 'id' => $orderId, ))->save($data) and $this->ajaxSuccess("发货内容已修改");
	    } elseif ( $order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SHIPPING ) { // 待发货
	        $data['order_status'] = DistributionShopOrderModel::ORDER_STATUS_SIGN;
	        // 更新产品销量
	        $productSalesSummary = M("DistributionShopOrderGoods")->where(array(
	            "order_id" => $orderId
	        ))->group("product_id")->field("product_id,sum(product_number) as totalName")->select();
	        foreach ($productSalesSummary as $v) {
	            M("DistributionShopGoods")->where("id=%d", $v['product_id'])->setInc("saled_count", 1);
	        }
	        // 设置发货状态
	        false !== $d->where(array( 'id' => $orderId, ))->save($data) and $this->ajaxSuccess("发货成功");
	    }
		$this->ajaxSuccess("发货失败");
	}
	
	// 订单评论
	public function commentAction() {
		$orderId = I('id');
		$productOrder = D( "DistributionShopOrder" )->getOrder($orderId, 0, $this->aid);
		$this->bindComment($productOrder);
		$this->assign("productOrder", $productOrder);
		$this->display();
	}
	
	// 绑定评价内容
	public function bindComment( &$productOrder ) {
		$productRateLists = M("DistributionShopRate")->where(array('order_id' => $productOrder['id'], 'reviewer' => DistributionShopRateModel::REVIEWER_BUYER))->select();
		foreach ( $productOrder['orderItems'] as $productId => &$v ) {
			foreach ( $v['items'] as $k => &$item ) {
				foreach ( $productRateLists as $rate) {
					if ( $rate['product_id']==$productId and $rate['order_goods_id']==$item['orderGoodsId'] ) {
						$item['buyer_rate_content'] = $rate['content'];
						$item['buyer_rate_time'] = $rate['create_time'];
						$item['statusOptions'] = $this->getOption(DistributionShopRateModel::$rateCheckStatus, $rate['status']);
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 卖家评价提交
	 *   格式:
	 * 		'order_id' => '订单id',
	 * 		'rates' => array('order_goods_id(订单商品编号)' => array(
	 *						 'content' => '评价内容',
	 *						),... ...);
	 
	public function commentPostAction() {
		$orderId = I('id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "ProductOrder" )->getOrder($orderId, 0, $this->aid)  or $this->ajaxError("未找到订单");
		false === D("ProductRate")->submitRate($order, $rates, $this->aid, ProductRateModel::REVIEWER_SALLER) and $this->ajaxSuccess("评价失败");
		$this->ajaxSuccess("评价成功");
	}*/
	
	public function checkCommentPostAction() {
		$orderId = I('id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "DistributionShopOrder" )->getOrder($orderId, 0, $this->aid)  or $this->ajaxError("未找到订单");
		false === D("DistributionShopRate")->checkRate( $order, $rates) and $this->ajaxSuccess("审核失败");
		$this->ajaxSuccess("审核成功");
	}
	
	/**
	 * 订单详细
	 */
	public function detialsAction() {
		$orderId = I("id", 0);
		$order = $this->getOrder($orderId);
		if ( in_array('deliver', $order['operates']) or DistributionShopOrderModel::ORDER_STATUS_SIGN) {
			$express = \Utuo\Express::getInstance();
			$expressNames = $express->getExpressname();
			$expressValues = array_values($expressNames);
			$order['deliverMethodRadio'] = $this->getRadio("deliver_method", $this->deliverMethod, $order['shipping_no']);
			$order['expressOptions'] = $this->getOption(array_combine($expressValues, $expressValues), $order['express_name'], "====请选择快递====");
		}
		$this->assign("order", $order);
		$this->display();
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrderAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "DistributionShopOrder" );
		$d->where ( array (
				"cid" => $this->aid,
				"id" => $orderId,
				"order_status" => DistributionShopOrderModel::ORDER_STATUS_PAY,
				"pay_status" => DistributionShopOrderModel::PAY_STATUS_NOT_PAID,
		) )->setField ( "order_status", DistributionShopOrderModel::ORDER_STATUS_CANCELED ) and $this->ajaxSuccess ( "取消成功" );
		$this->ajaxError ( "取消失败" );
	}
	
	/**
	 * 代理买家确认收货
	 */
	public function actForSignAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "DistributionShopOrder" );
		$order = $d->find( $orderId );
		if($order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN) {
			// 更新订单状态
			$data = array("order_status" => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
						"take_time" => time(),
						"deal_time" => time(),);
			if( false !== $d->where ( array ( "uid" => $order['uid'], "id" => $orderId, ) )
							->save ( $data ) ) {
						$order = array_merge($order, $data);
						$eventData = array('order' => $order);
						tag('disorder_completed', $eventData);
						$this->ajaxSuccess ( "交易成功" );
			}
		} else {
			$this->ajaxError ( "非已发货状态，不能完成收货操作。" );
		}
		$this->ajaxError ( "提交失败，请重新确认收货" );
	}
	
	/**
	 * 确认用户的退款
	 */
	public function confirmRefundAction() {
		$orderId = I ( "id", 0, "int" ); // 订单id(*)
		$refundId = I ( "refundId", 0, "int" ); // 退款id
		$condition = array(
			'a.cid' => $this->aid,
			'a.id' => $orderId,
			'b.status' => 0,
		);
		$refundId and $condition['b.id'] = $refundId;
		// 退款申请列表
		$orderRefundList = M ( "DistributionShopOrder a" )->join("__DISTRIBUTION_SHOP_REFUND__ b on a.order_id=b.orderNo")
													->where( $condition )
													->field("a.*,b.id as refundId,b.refundNo,b.refundTotalFee,b.all")
													->select();
		// 循环确认退款
		foreach ( $orderRefundList as $orderRefund ) {
			$error = 0;
			if ( $orderRefund['all']  ) { // 全款退款处理
				$data = array();
				$pay = \Utuo\Pay::getInstance($orderRefund['pay_method'], DistributionShopPayLogic::getApiConfig($this->aid, array('paymentMethod' => $orderRefund['pay_method'],)));
				if ( $orderRefund['pay_method'] == 'WxTenpay'  ) {
					// 要更新的状态
					$data['order_status'] = DistributionShopOrderModel::ORDER_STATUS_REFUND_PROCESSING;
					$data['refund_status'] = 1;
					// 调用接口申请退款
					if ( false === $pay->refund(null, $orderRefund['refundNo'], $orderRefund['actual_cost'], $orderRefund['refundTotalFee'], array(
							'orderNo' => $orderRefund['order_id'],
					)) ) {
						$error = $pay->getError();
					}
				} else {
					// 要更新的状态
					$data['order_status'] = DistributionShopOrderModel::ORDER_STATUS_REFUND_SUCCESS;
					$data['pay_status'] = DistributionShopOrderModel::PAY_STATUS_REFUND;
					$data['refund_status'] = 2;
				}
				// 调用接口无误时更新
				if ( !$error ) {
					if ( false !== M("DistributionShopRefund")->where(array('id'=>$orderRefund['refundId'], 'status'=>0))->setField("status", 1) ) { // 设置退款成功
						if ( false !== M ( "DistributionShopOrder" )->where(array( 'id' => $orderRefund['id'] ))->save( $data ) ) { // 设置订单退款处理中
							
						} else {
							$error = "退款订单状态更新失败";
						}
					} else {
						$error = "退款申请更新失败";
					}
				}
			}
			$error and $this->ajaxError("退款确认失败:".$error);
		}
		$this->ajaxSuccess("退款确认成功");
	}
	
	/**
	 * 获得指定用户的推广订单列表
	 */
	public function showUserOrderListAction() {
		$pageSize = $this->getPageSize();
		$p = $this->getPage();
		$uid = I('uid', 0, "intval");
		$m = M("DistributionShopOrderGoods goods")->join("__DISTRIBUTION_SHOP_ORDER__ orders on goods.order_id=orders.id", "LEFT")
											->where(array(
													'orders.order_status' => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
													'_complex' => array(
															'goods.reward_uids'=>array('exp', "!='' and goods.reward_uids is not null and find_in_set({$uid}, goods.reward_uids)"), // 在参与返佣的用户之内
															'goods.reward_uids_dealer'=>array('exp', "!='' and goods.reward_uids_dealer is not null and find_in_set({$uid}, goods.reward_uids_dealer)"), // 在参与返佣的用户之内
															'_logic' => 'or',
													),
											));
		$n = clone $m;
		$count = $n->count();
		$orderGoodsLists = $m->field("goods.*,orders.order_id as orderNo")->limit($pageSize)->page($p)->select();

		foreach ( $orderGoodsLists as $k => &$v ) {
			$v['bonusInfo'] = DistributionShopOrderModel::bonusInfo( $v );
			$v['bonusUsers'] = M("WechatUser")->where(array('id' => array("in", array_keys($v['bonusInfo']))))->getField("id,nickname,face,openId");
		}
		$this->showPage($count, $pageSize);
		$this->assign("orderGoodsLists", $orderGoodsLists);
		$this->display();
	}
	
	/**
	 * 订单退款(强行标记退款动作)
	 */
	public function refundOrderAction() {
		$this->display();
	}
	
	/**
	 * 订单退款(强行标记退款动作)
	 */
	public function refundOrderPostAction() {
		$orderNo = I('order_no', '-1');
		if ( M("DistributionShopOrder")->where(array(
			'order_id' => $orderNo,
			'cid' => $this->aid,
		))->save(array(
			'refund_status' => DistributionShopOrderModel::REFUND_STATUS_REJECT,
			'pay_status' => DistributionShopOrderModel::PAY_STATUS_REFUND,
			'order_status' => DistributionShopOrderModel::ORDER_STATUS_REFUND_SUCCESS,
		)) ) {
			$this->ajaxSuccess('已标记为退款成功');			
		} 
		$this->ajaxError('操作失败');
	}
	
	private function setActionLink() {
		foreach ($this->orderTypes as $k => $v) {
			$this->setLinkNav("$v", U('DistributionShopOrder/index', array('type'=>$k)));
		}
	}
	
	// 获得订单操作
	private function getOperate( &$v ) {
		$operates = array();
		
		if ( $v['buy_method'] == DistributionShopOrderModel::BUY_METHOD_GIFTS ) { // 送礼订单
			if(($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SHIPPING) and ($v['buy_status'] == DistributionShopOrderModel::BUY_METHOD_COQUETRY) ) {
				$operates[] = "deliver";
			}
		} elseif(($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SHIPPING)) {
			$operates[] = "deliver";
		}
		
		if ( $v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_REFUND_APPLY ) {
			$operates[] = "refund_apply";
		}
		
		if ( $v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_REFUND_PROCESSING ) {
			$operates[] = "refund_search";
		}
			 
		if (  $v ['order_status'] == DistributionShopOrderModel::ORDER_STATUS_PAY and $v ['pay_status'] == DistributionShopOrderModel::PAY_STATUS_NOT_PAID ) {
			$operates[] = "cancel";
		}
		
		if ( $v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN and time() > $v['expect_take_time']) {
			$operates[] = "act_for_sign";
		}
		
		if($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_COMPLETED and in_array($v['rate_status'], array(DistributionShopRateModel::RATE_STATUS_UNRATE, DistributionShopRateModel::RATE_STATUS_BUYER))) {
			$operates[] = "check_comment";
		}
		
		$v['operates'] = $operates;
	}
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
	 */
	private function getOrder( $id ) {
		$order = M ( "DistributionShopOrder orders" )->join( "__WECHAT_USER__ user on orders.uid=user.id", "LEFT")
					->join( "__AGENT__ agent on agent.id = orders.agent_id", "LEFT" )
					->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
					->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
					->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
					->field ( "orders.*,user.nickname as userName,province.name as provinceName, city.name as cityName, area.name as areaName, agent.name as agentName" )
					->where ( "orders.id=%d", $id )->find ();
		if ( !$order ) return null;
		$orders = array (
				&$order
		);
		$this->bindOrderDetail ( $orders );
		return $order;
	}
	
	/* 绑定订单详细 */
	private function bindOrderDetail(&$orderLists) {
		/* 关联订单商品 */
		$dProductOrder = D ( "My/DistributionShopOrder" );
		$mProductGoods = M ( "DistributionShopOrderGoods" );
		foreach ( $orderLists as &$v ) {
			/* 处理不同的购买状态 */
			if ( $v['buy_method'] == DistributionShopOrderModel::BUY_METHOD_GIFTS ) {
				$gifts = M("DistributionShopGifts gifts")->where ( "gifts.order_id = {$v['id']}" )->find();
				$v['buy_status'] = $gifts['buy_status'];
				$v['to_uid'] = $gifts['to_uid'];
			} elseif ( $v['buy_method'] == DistributionShopOrderModel::BUY_METHOD_COQUETRY ) {
				
			}
			// 绑定显示状态
			$v ["orderStatusName"] = $dProductOrder->getOrderShowStatus ( $v );
			// 订单佣金信息
			$bonusInfo = DistributionShopOrderModel::bonusInfo($v);
			if ( $bonusInfo ) {
				$bonusUserIds = array_keys($bonusInfo);
				$bonusUsers = M("WechatUser")->where(array('id' => array("in", $bonusUserIds)))->getField("id,nickname,face,openId");
				$this->assign("bonusInfo", $bonusInfo);
				$this->assign("bonusUser", $bonusUsers);
			}
			// 订单代理佣金信息
			$bonusInfoAgent = DistributionShopOrderModel::bonusInfoAgent($v);
			if ( $bonusInfoAgent ) {
			    $bonusUserAgentIds = array_keys($bonusInfoAgent);
			    $bonusUsersAgent = M("Agent agent")->join("__WECHAT_USER__ user on agent.wechat_uid=user.id", "LEFT")->where(array('agent.id' => array("in", $bonusUserAgentIds)))->getField("agent.id,user.nickname,user.face,user.openId,agent.level as agentLevel");
			    $this->assign("bonusInfoAgent", $bonusInfoAgent);
			    $this->assign("bonusUserAgent", $bonusUsersAgent);
			}
			// 获得操作
			$this->getOperate($v);
			// 绑定订单商品
			$orderGoods = $mProductGoods->where ( "order_id=%d", $v ['id'] )->select ();
			foreach ( $orderGoods as &$v0 ) {
				$v ['orderItems'] [$v0 ['product_id']] or $v ['orderItems'] [$v0 ['product_id']] = array (
						'productId' => $v0 ['product_id'],
						'productName' => $v0 ['product_name'],
						'items' => array ()
				);
				$v ['orderItems'] [$v0 ['product_id']] ['items'] [] = array (
						'productPic' => $v0 ['product_pic'],
						'productNumber' => $v0 ['product_number'],
						'productPrice' => $v0 ['product_price'],
						'productAttr' => $v0 ['product_attr']
				);
			}
		}
	}
	
	/**
	 * 获得单元格格式
	 * @param unknown $fieldCfg
	 * @return string
	 */
	private function getCellFormat( $fieldCfg ) {
		if( $fieldCfg['type'] == 'string' ) {
			return \PHPExcel_Cell_DataType::TYPE_STRING;
		}
		return \PHPExcel_Cell_DataType::TYPE_STRING;
	}
	
	
	/**
	 * 获得数据展示格式
	 * @param unknown $value
	 * @param unknown $fieldCfg
	 * @return string|unknown
	 */
	private function getShowData($value, $fieldCfg) {
		if( $fieldCfg['type'] == 'datetime' ) {
			return date( $fieldCfg['format'], $value);
		}
		return $value;
	}
	
}